import i18n from "i18n-js";
import language from '@/models/language';
import { IProduct, getItemForPk } from '@/config/product';

const matchLanguage = (targetLanguage: any, languageKey: string) => {
  // 强匹配，找不到，降级到两位，再找不到返回默认英文，英文也没有就null
  return (
    targetLanguage[languageKey]
    || targetLanguage[languageKey.substring(0, 2)]
    || targetLanguage.en
    || null
  );
};


/**
 * 产品文案翻译
 *
 * @export
 * @param {string} key - 文案的Key
 * @param {Object|string} product - 产品对象或产品 PK
 * @returns {string} - 经过翻译文案，没找到返回对应Key
 */
export default function productI18n(key: any, product: IProduct, opts?: any) {
  const productItem = product instanceof Object ? product : (getItemForPk(product) as IProduct);
  if (productItem) {
    /**
     * 先在产品里面找翻译
     * 找不到去模版找
     */
    const languageData = matchLanguage(productItem.language, language.key);
    if (languageData && languageData[key]) {
      return languageData[key];
    }
  }
  return i18n.t(key)
  // const template = templates.getComponent({
  //   id: productItem.templateId,
  //   url: productItem.templateDownloadUrl as string,
  // });
  // if (template && template.i18n) {
  //   return template.i18n.t(key, { locale: language.key, ...(opts || {}) });
  // }
  // return key;
}
